import logging
from django.db import transaction
from django.db.models import Q
from rest_framework import status
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from finance.api.mobile.mobile_serializers import MobileFundBillSerializer
from finance.api.utils import update_account
from finance.models import FundBill
from users.api.utils import get_user_by_request

logger = logging.getLogger("django")


class MobileFundBillViewSet(ModelViewSet):
    """资金账单"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = FundBill.objects.filter(category=0)
    serializer_class = MobileFundBillSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        user = get_user_by_request(self.request)

        if user and not user.is_superuser:
            queryset = queryset.filter(user_id=user.id)

        name = self.request.query_params.get("name", None)

        search_date = self.request.query_params.getlist("search_date[]", None)

        if name:
            queryset = queryset.filter(Q(employee__name__contains=name) | Q(order_no__contains=name))
        # 时间
        if search_date and len(search_date) == 2:
            queryset = queryset.filter(order_time__range=(search_date[0], search_date[1]))

        return queryset

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        with transaction.atomic():
            save_id = transaction.savepoint()
            try:
                if instance.verify == 1:
                    self.update_account(instance)
                self.perform_destroy(instance)
            except Exception as e:
                logger.info("Destroy: {}".format(e))
                transaction.savepoint_rollback(save_id)

            transaction.savepoint_commit(save_id)

        return Response(status=status.HTTP_204_NO_CONTENT)

    def update_account(self, obj):
        if obj.category == 0:
            if obj.money != obj.repayment:
                update_account(obj.account_id, obj.money * -1)


